package com.jawmask.android.discover.ui;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Address;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.jawmask.android.discover.R;
import com.jawmask.android.discover.bean.GPSLocation;
import com.jawmask.android.discover.bean.SearchRequest;
import com.jawmask.android.discover.bean.SearchResult;
import com.jawmask.android.discover.bean.task.FetchImageTask;
import com.jawmask.android.discover.bean.task.PlaceSearchTask;
import com.jawmask.android.discover.ui.widgets.PullToRefreshListView;
import com.jawmask.android.discover.utils.ImageCacheUtils;
import com.jawmask.android.discover.utils.UserSession;

public class SearchResultActivity extends BaseListActivity implements OnClickListener {

	private ImageView nextButton, backButton;
	private TextView searchInputTitle;

	private List<SearchResult> searchResult;
	private boolean firstTime = true;
	private String userSearchInput;
	private Map<String, List<SearchResult>> pageTokenMap = new HashMap<String, List<SearchResult>>();
	private String nextPageToken;

	private PullToRefreshListView pullToRefreshListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result);

		nextButton = (ImageView) findViewById(R.id.nextPageButton);
		backButton = (ImageView) findViewById(R.id.backPageButton);
		searchInputTitle = (TextView) findViewById(R.id.searchTextTitle);

		userSearchInput = getIntent().getStringExtra(getString(R.string.extra_key_search_plcae_user_input));
		searchInputTitle.setText(userSearchInput);

		pullToRefreshListView = (PullToRefreshListView) getListView();
		pullToRefreshListView.

		loadPageData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.search_result_menu, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getItemId() == R.id.menu_sort_by_popularity) {
			if (SearchResultActivity.this.searchResult != null) {
				Collections.sort(searchResult, new Comparator<SearchResult>() {
					@Override
					public int compare(SearchResult lhs, SearchResult rhs) {
						if (lhs.getRating() > rhs.getRating())
							return firstTime ? -1 : 1;
						else if (lhs.getRating() < rhs.getRating())
							return firstTime ? 1 : -1;
						return 0;
					}
				});
				firstTime = !firstTime;
				setListAdapter(new SearchResultAdapter(SearchResultActivity.this, searchResult));
			}
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected void onListItemClick(ListView listView, View selectedView, int position, long selectedItemId) {
		SearchResult searchResult = (SearchResult) getListAdapter().getItem(position);

		Intent intent = new Intent(this, SearchResultDetails.class);
		intent.putExtra(getString(R.string.extra_key_search_plcae_item), searchResult);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.backPageButton:
		case R.id.nextPageButton:
			loadPageData();
			break;
		}
	}

	private final class SearchResultAdapter extends ArrayAdapter<SearchResult> {

		public SearchResultAdapter(Context context, List<SearchResult> searchResult) {
			super(context, -1, -1, searchResult);
		}

		@Override
		public SearchResult getItem(int position) {
			return super.getItem(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				view = View.inflate(SearchResultActivity.this, R.layout.search_result_item, null);

				SearchResultViewHolder searchResultViewHolder = new SearchResultViewHolder();
				searchResultViewHolder.searchResultIcon = (ImageView) view.findViewById(R.id.resultIcon);
				searchResultViewHolder.searchResultName = (TextView) view.findViewById(R.id.resultName);
				searchResultViewHolder.searchResultRating = (RatingBar) view.findViewById(R.id.resultRating);

				view.setTag(searchResultViewHolder);
			}

			final SearchResultViewHolder searchResultViewHolder = (SearchResultViewHolder) view.getTag();
			SearchResult searchResult = getItem(position);

			String searchResultIconPath = searchResult.getIconPath();
			searchResultViewHolder.searchResultIcon.setTag(searchResultIconPath);
			Bitmap bitmap = ImageCacheUtils.getInstance().getImage(searchResultIconPath);
			if (bitmap != null) {
				searchResultViewHolder.searchResultIcon.setImageBitmap(bitmap);
			} else {
				new FetchImageTask(SearchResultActivity.this, searchResultViewHolder.searchResultIcon).execute(searchResultIconPath);
			}

			searchResultViewHolder.searchResultName.setText(searchResult.getName());
			searchResultViewHolder.searchResultRating.setRating(searchResult.getRating());

			return view;
		}
	}

	private final class SearchResultViewHolder {
		ImageView searchResultIcon;
		TextView searchResultName;
		RatingBar searchResultRating;
	}

	private final PlaceSearchTask placeSearchTask = new PlaceSearchTask(SearchResultActivity.this) {

		protected void onPreExecute() {
			waitForData(getString(R.string.notification_msg_searching, userSearchInput));
		}

		protected void onPostExecute(List<SearchResult> searchResult) {
			receivedData();

			if (searchResult != null && !searchResult.isEmpty()) {
				SearchResultActivity.this.searchResult = searchResult;
				SearchResult searchResult2 = searchResult.get(0);
				String nextPageToken = searchResult2.getNextPageToken();
				if (nextPageToken == null) {
					nextButton.setEnabled(false);
				} else {
					nextButton.setEnabled(true);
				}

				pageTokenMap.put(nextPageToken, searchResult);
				nextPageToken = searchResult2.getNextPageToken();
				setListAdapter(new SearchResultAdapter(SearchResultActivity.this, searchResult));
			}
		};
	};

	private void loadPageData() {
		if (pageTokenMap.isEmpty()) {
			fetchSearchItems();
		} else {
			List<SearchResult> searchResult = pageTokenMap.get(nextPageToken);
			setListAdapter(new SearchResultAdapter(SearchResultActivity.this, searchResult));
		}
	}

	private void fetchSearchItems() {
		SearchRequest searchRequest = new SearchRequest();
		searchRequest.setLocationFromDevice(true);
		searchRequest.setUserSearchText(userSearchInput);

		Address userAddress = UserSession.getInstance().getUserAddress();
		GPSLocation userLocation = new GPSLocation();
		userLocation.setLatitude(userAddress.getLatitude());
		userLocation.setLongitude(userAddress.getLongitude());
		searchRequest.setUserLocation(userLocation);

		placeSearchTask.execute(searchRequest);
	}
}
